package cool.taomu.web.controller

import com.google.gson.Gson
import cool.taomu.web.entity.Message
import cool.taomu.web.entity.StockIndustryDataEntity
import cool.taomu.web.entity.StockIndustryEntity
import cool.taomu.web.entity.sina.SinaStock
import cool.taomu.web.utils.ListPageUtils
import cool.taomu.web.utils.StockDataUtils
import java.util.ArrayList
import java.util.HashMap
import java.util.Map

class StockDataController {
	def static getStockIndustryList(String message) {
		val h2 = StockDataUtils.getInstance().getH2();
		var industrys = h2.select("select industry from stock_data group by industry order by industry desc",Map);
		val indlist = newArrayList();
		industrys.forEach [
			var ind = it.get("INDUSTRY") as String
			var stock = h2.select("select code from stock_data where INDUSTRY=?",Map, #[ind]);
			var codes = stock.map [
				return it.get("CODE") as String;
			]
			var String indKey = ind.nullOrEmpty ? "其他" : ind;
			var sie = new StockIndustryEntity(indKey, codes);
			var pageSize = sie.codes.size / 800;
			val stocklist = newArrayList;
			val codelist = newArrayList();
			for (i : 0 .. pageSize) {
				ListPageUtils.page(i + 1, 800, sie.codes, [ j, v |
					codelist.add(v);
				])
				var code = codelist.join(",").replace(".", "");
				var res = SinaStock.getStockData(code);
				stocklist.addAll(res);
				codelist.clear();
			}
			indlist.add(new StockIndustryDataEntity(indKey, stocklist));
		];
		var Message msg = new Message();
		msg.setType("0");
		msg.setData(indlist);
		var String a = new Gson().toJson(msg);
		return a;
	}

	def getStockDataList(String message) {
		System.err.println(message);
		var h2 = StockDataUtils.getInstance().getH2();
		var ArrayList<HashMap<String, Object>> results = h2.select("select * from stock_data",Map) as ArrayList;
		var pageSzie = results.size / 800;
		var list = newArrayList();
		val codes = newArrayList();
		for (i : 0 .. pageSzie) {
			ListPageUtils.page(i + 1, 800, results, [ j, v |
				codes.add(v.get("CODE"));
			])
			var code = codes.join(",").replace(".", "");
			var res = SinaStock.getStockData(code);
			list.addAll(res);
			codes.clear;
		}
		var Message msg = new Message();
		msg.setType("0");
		msg.setData(list);
		var String a = new Gson().toJson(msg);
		return a;

	}
}
